package com.redis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by buguniao on 16/4/4.
 */
public class TestSemaphore {
    public static void main(String[] args) {
        final JedisPool pool = new JedisPool("localhost", 7000);

        final RedisSemaphore semaphore = new RedisSemaphore();
        int size = 30;
        ExecutorService service = Executors.newFixedThreadPool(size);

        for (int i = 0; i < size; i++) {
            service.submit(new Runnable() {
                private int num = 0;

                public void run() {
                    Jedis jedis = pool.getResource();
                    while (true) {
                        String clientId = semaphore.acquire(jedis);
                        if (clientId == null) {
                            System.out.println((num++) + " - " + Thread.currentThread().getName() + " 获取到信号量 " + clientId);
                        } else {
                            System.out.println((num++) + " - " + Thread.currentThread().getName() + " 获取到信号量 " + clientId);
                            try {
                                Thread.sleep(3000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            semaphore.release(jedis,clientId);
                            System.out.println((num++) + " - " + Thread.currentThread().getName() + " 释放信号量 " + clientId);
                        }

                    }
                }
            });
        }

        pool.close();
    }
}
